package com.gmcloud.plugin.captcha.controller;

import com.gmcloud.plugin.captcha.model.ResponseModel;
import com.gmcloud.plugin.captcha.service.CaptchaService;
import com.gmcloud.plugin.captcha.utils.StringUtils;
import com.gmcloud.plugin.captcha.vo.CaptchaVO;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/31 0:16
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private final CaptchaService captchaService;

    public CaptchaController(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    @PostMapping
    public ResponseModel get(@RequestBody CaptchaVO data, ServerHttpRequest request) {
        data.setBrowserInfo(getRemoteId(request));
        return captchaService.get(data);
    }

    @PostMapping("/check")
    public ResponseModel check(@RequestBody CaptchaVO data, ServerHttpRequest request) {
        data.setBrowserInfo(getRemoteId(request));
        return captchaService.check(data);
    }

    @PostMapping("/verify")
    public ResponseModel verify(@RequestBody CaptchaVO data, ServerHttpRequest request) {
        return captchaService.verification(data);
    }

    public static final String getRemoteId(ServerHttpRequest request) {
        String xfwd = request.getHeaders().getFirst("X-Forwarded-For");
        String ip = getRemoteIpFromXfwd(xfwd);
        String ua = request.getHeaders().getFirst("user-agent");
        if (StringUtils.isNotBlank(ip)) {
            return ip + ua;
        }
        return request.getRemoteAddress() + ua;
    }

    private static String getRemoteIpFromXfwd(String xfwd) {
        if (StringUtils.isNotBlank(xfwd)) {
            String[] ipList = xfwd.split(",");
            return StringUtils.trim(ipList[0]);
        }
        return null;
    }
}
